package com.csist.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csist.mapper.UserMapper;
import com.csist.pojo.User;
import com.csist.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@ResponseBody
public class Api {
    @Autowired
    UserMapper userMapper;

    /**
     * login method
     * @param username
     * @param password
     * @return Return user on success
     */
    @RequestMapping("/login")
    public User login(String username,String password){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        wrapper.eq("password",password);
        User user = userMapper.selectOne(wrapper);
        if (user!=null){
            user.setToken(JwtUtil.createToken());
        }
        return user;
    }

    /**
     * 验证token
     * @param request
     * @return true:验证成功,false:验证失败
     */
    @RequestMapping("/checkToken")
    public Boolean getUserSession(HttpServletRequest request){
        String token = request.getHeader("token");
        return JwtUtil.checkToken(token);
    }
}
